import React, { createRef } from 'react';
import { connect } from 'dva';
import { Button, Dropdown, Menu, Icon, Row, Col } from 'antd';
import styles from './style.less';
import AxSimpleSearch from '@/components/AxForm/AxSearchForm/AxSimpleSearch';
import { axhelper } from '@/shared/axhelper';
// import IconFont from '@/assets/iconfont/index';

/** 自定义列表顶部操作按钮
 *  @params buttons 操作按钮
 *  @params advanceSearch 是否展示高级查询（默认true）
 *  @params searchOption 查询选项
 *  @params handleSearch 查询方法
 */
@connect(({ global, loading }) => ({
  modelState: global, // 将实体listTableList中的state数据绑定到props
  loading: loading.models.global,
}))
class AxOperationButton extends React.Component {
  constructor(props) {
    super(props);
    axhelper.getPermission();
  }

  handleClientWidth = () => {
    const { dispatch } = this.props;
    return dispatch({
      type: `global/readClientWidth`,
      params: {
        clientWidth: window.document.body.clientWidth,
      }
    });
  }

  componentDidMount() {
    this.handleClientWidth();
    window.onresize = this.handleClientWidth;
  }

  render() {
    const permissions = parseInt(localStorage.getItem('ax-auth-permissions'));
    const {
      buttons,
      searchOption,
      advanceSearch,
      handleSearch,
      handleVisible,
      handleResetSearch,
      searchFormValues,
      modelState: { clientWidth },
    } = this.props;
    /** 有权限的按钮 */
    let permissionButtons = buttons.filter(
      i => !i.permissions || (permissions & i.permissions) > 0,
    );
    /** 普通按钮 */
    const normalButtons = permissionButtons.filter(
      i => !i.group && !i.search && !i.export && !i.io,
    );
    /** 分组按钮 */
    const groupButtons = permissionButtons.filter(i => i.group === true);
    /** 导出按钮（直接网页导出） */
    const exportButton = permissionButtons.find(i => i.export === true);
    /** 导入导出按钮（后端导入导出） */
    const ioButtons = permissionButtons.filter(i => i.io === true);
    let searchSpan = ioButtons && ioButtons.length > 0 ? 10 : 12;

    /** 控制按钮的折叠 */
    let count = Infinity;
    normalButtons.forEach((i) => {
      i.collapse = 'false';
    });
    groupButtons.forEach((i) => {
      i.collapse = 'false';
    });
    if (clientWidth <= 904) {
      count = 2
    }
    else if (clientWidth <= 1142) {
      count = 3
    }
    else if (clientWidth <= 1378) {
      count = 4
    }
    else if (clientWidth <= 1610) {
      count = 5
    }
    else if (clientWidth <= 1740) {
      count = 6
    }

    if (count !== Infinity) {
      normalButtons.forEach((i, idx) => {
        if (idx + 1 >= count) {
          i.collapse = 'true';
        }
      });
      if (normalButtons.length >= count) {
        groupButtons.forEach((i) => {
          i.collapse = 'true';
        });
      }
    }
    const collapseButtons = [...normalButtons, ...groupButtons].filter(i => i.collapse === 'true');
    const noCollapseNormalButtons = normalButtons.filter(i => i.collapse === 'false');
    const noCollapseGroupButtons = groupButtons.filter(i => i.collapse === 'false');

    const handleMore = (key, items) => {
      const item = items[key];
      item && item.onClick && item.onClick();
    };

    const getMoreBtn = ({ items }) => (
      <Dropdown
        trigger={['click']}
        overlay={
          <Menu onClick={({ key }) => handleMore(key, items)}>
            {items.map((i, idx) => (
              <Menu.Item key={idx} disabled={i.disabled} hidden={i.hidden}>
                <Icon type={i.icon} />
                {i.text}
              </Menu.Item>
            ))}
          </Menu>
        }
      >
        {items.length > 0 ? (
          <Button
            size={window.ax.config.size}
            type='ghost'
          >
            更多操作 <Icon type="down" />
          </Button>
        ) : null}
      </Dropdown>
    );

    return (
      <div className={styles.tableListOperator}>
        <Row>
          {/* 显示按钮 */}
          <Col span={12}>
            {noCollapseNormalButtons.map((i, index) => {
              const { text, icon, spin, group, ...rest } = i;
              return (
                <Button
                  size={window.ax.config.size}
                  key={index}
                  {...rest}
                  type='ghost'
                >
                  <Icon
                    type={icon}
                    spin={spin}
                  />{text}
                </Button>
              );
            })}
            {noCollapseGroupButtons && noCollapseGroupButtons.length > 0 && getMoreBtn({ items: noCollapseGroupButtons })}
            {/* 折叠按钮 */}
            {collapseButtons.length > 0 &&
              <Dropdown
                trigger={['click']}
                overlay={
                  <Menu onClick={({ key }) => handleMore(key, collapseButtons)}>
                    {collapseButtons.map((i, idx) => (
                      <Menu.Item key={idx} disabled={i.disabled} hidden={i.hidden}>
                        <Icon type={i.icon} />
                        {i.text}
                      </Menu.Item>
                    ))}
                  </Menu>
                }
              >
                <Button
                  size={window.ax.config.size}
                  type='ghost'
                >
                  <Icon type="more" />
                </Button>
              </Dropdown>}
          </Col>

          {/* 简单查询 */}
          <Col span={12}>
            <AxSimpleSearch
              items={searchOption}
              searchFormValues={searchFormValues}
              advanceSearch={advanceSearch}
              handleSearch={handleSearch}
              handleVisible={handleVisible}
              handleResetSearch={handleResetSearch}
              ioButtons={ioButtons}
              exportButton={exportButton}
            />
          </Col>
        </Row>
      </div>
    );
  }
}

export default AxOperationButton;
